package net.bat.dao;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import net.bat.entity.IdEntity;

import org.springframework.beans.BeanWrapperImpl;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@Transactional(value = "transactionManager", noRollbackFor = { NoResultException.class })
public class UserDAO extends BaseJpaDao {
	public enum Action {
		ADD, REMOVE, UPDATE
	}

	@PersistenceContext(unitName = "entityManagerFactory")
	private EntityManager entityManager;

	@Override
	public EntityManager getEntityManager() {
		// TODO Auto-generated method stub
		return entityManager;
	}

	public <T extends IdEntity> T load(Class<T> entity, Map<String, Object> rmap) throws Exception {
		Object id = rmap.get("id");
		T eo = null;
		if (id != null) {
			eo = find(entity, Long.parseLong(id.toString()));
		}
		if (eo == null) {
			eo = entity.newInstance();
		}
		BeanWrapperImpl beanWrapper = new BeanWrapperImpl(eo);
		beanWrapper.setPropertyValues(rmap);
		return eo;
	}

	/**
	 * 带操作日志的保存
	 * 
	 * @throws ClassNotFoundException
	 */
	@Transactional
	public <T extends IdEntity> T update(String entity_name, Long id, Map<String, Object> rmap) throws Exception {
		Class<T> entity = classForName(entity_name);
		T eo = find(entity, id);
		// entity不存在,新建之
		if (eo == null) {
			return add(entity_name, rmap);
		}
		BeanWrapperImpl beanWrapper = new BeanWrapperImpl(eo);
		beanWrapper.setPropertyValues(rmap);
		save(eo);
		return eo;
	}

	@Transactional
	public <T extends IdEntity> T add(String entity_name, Map<String, Object> rmap) throws Exception {
		Class<T> entity = classForName(entity_name);
		T eo = entity.newInstance();
		rmap.remove("id");
		BeanWrapperImpl beanWrapper = new BeanWrapperImpl(eo);
		beanWrapper.setPropertyValues(rmap);
		save(eo);
		return eo;
	}

	@Transactional
	public <T extends IdEntity> void remove(String entity_name, Object[] ids) throws Exception {
		Class<T> entity = classForName(entity_name);
		Long[] lids = new Long[ids.length];
		int pos = 0;
		for (Object id : ids) {
			Long lid = Long.parseLong(id.toString());
			lids[pos++] = lid;
		}
		delete(entity, lids);
	}

	/**
	 * @param entity
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static <T extends IdEntity> Class<T> classForName(String entity) throws ClassNotFoundException {
		return (Class<T>) Class.forName(getEntityFullName(entity));
	}

	/**
	 * 补齐默认包路径全名
	 *
	 * @param entity
	 * @return
	 */
	public static String getEntityFullName(String entity) {
		if (entity.indexOf(".") == -1) {
			return "net.bat.entity." + entity;
		} else {
			return entity;
		}
	}

}
